home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11955 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: rain.fr!world-net!usenet
  2. From: Frederic LACHASSE <lachass@worldnet.fr>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Explicit copy constructor calls illegal?
  5. Date: Sun, 17 Mar 1996 07:35:13 +0000
  6. Organization: World-Net information exchange, Internet provider.
  7. Message-ID: <VA.0000006a.0002829a@fred>
  8. References: <4i9tp8$fgt@reznor.larc.nasa.gov>
  9. Reply-To: lachass@worldnet.fr
  10. NNTP-Posting-Host: client122.sct.fr
  11. X-Newsreader: Virtual Access by Ashmount Research Ltd, http://www.ashmount.com
  12.  
  13. In article <4i9tp8$fgt@reznor.larc.nasa.gov>, lance@jitter.larc.nasa.gov 
  14. (Michael Lance) wrote:
  15. > Hey!
  16. > I am not a C++ newbie, but am feeling like I missed something:
  17. > Why can I not make an explicit call to a copy constructor from a class
  18. > member function?  To define my terminology, the copy constructor is the
  19. > function:
  20. >                 MyClass(const MyClass&)
  21. > When I try to do this (just trying to re-use code - it is there, why not?),
  22. > a new instance of the class is instantiated SOMEWHERE, but a cout in the
  23. > constructor does NOT reflect it.  The copy constructor properly assigns
  24. > the member variables of the instance, and the destructor registers its
  25. > destruction!
  26. > Any clues, or am I violating a basic tenet?  Lippman 2nd. edition is no
  27. > help here.  
  28. There is a hack to call a constructor: use the placement new operator. It is 
  29. defined as:
  30.  
  31. inline void* operator new(size_t, void* ptr) { return ptr; }
  32.  
  33. So you can call a constructor (for example a copy constructor) on an existing 
  34. piece of memory:
  35.  
  36.  MyClass a;
  37.  char space[sizeof(MyClass)];
  38.  MyClass* pcopy = new(space) MyClass(a);
  39.  
  40. Explicit calling of the destructor is allowed so:
  41.  
  42.  pcopy->~MyClass();
  43.  
  44. will destroyed this object.
  45.  
  46. Of course, that's dangerous pratice, so think twice before doing that.
  47.  
  48.  Frederic LACHASSE (ECP 86)
  49.  CompuServe: 100530,2005
  50.  Internet: lachass@worldnet.fr
  51.  
  52.